package com.itheima.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

/**
 * 自定义元数据对象处理器
 */
//加注解让spring框架来管理这个处理器
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    //方法二：使用自动注入HttpServletRequest或者 HttpSession
    //自动注解适用于现在代码，到时候用到Redis就要线程隔离
   /* @Autowired
    HttpSession session;*/
    //先运行完controller再运行insertFill
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("公共字段自动填充[insert]...");
        log.info(metaObject.toString());

///((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //设置插入数据时以下属性，自动填充
        metaObject.setValue("createTime", LocalDateTime.now());
        metaObject.setValue("updateTime", LocalDateTime.now());
        metaObject.setValue("createUser", BaseContext.getCurrentId());
        metaObject.setValue("updateUser", BaseContext.getCurrentId());
        /*metaObject.setValue("createUser", session.getAttribute("employee"));
        metaObject.setValue("updateUser", session.getAttribute("employee"));*/
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("公共字段自动填充[update]...");
        log.info(metaObject.toString());
        //测试三个类是否属于同一个线程
        long id = Thread.currentThread().getId();
        log.info("线程id为：{}",id);

        metaObject.setValue("updateTime", LocalDateTime.now());
        metaObject.setValue("updateUser", BaseContext.getCurrentId());
    }
}
